<?php

namespace app\store\controller\apps\sign;

use app\common\library\helper;
use app\store\controller\Controller;
use app\store\model\Setting as SettingModel;
use app\store\model\Sign as SignModel;
use think\Cache;

/**
 * 签到
 * Class Store
 * @package app\store\controller
 */
class Sign extends Controller
{
    public function index()
    {
        $sign = new SignModel();
        $list = $sign->getList($this->getData(), ['user']);
        return $this->fetch('index', compact('list'));
    }

    /**
     * 保存签到配置
     * @return array|bool|\think\response\Json
     */
    public function sign()
    {
        if (!$this->request->isAjax()) {
            $values = SettingModel::getItem('sign');
//            dump($values);die;
            return $this->fetch('sign',compact('values'));
        }
        $model = new SettingModel();
        $param = $this->postData('sign');
        if ($param['is_lianxu'] == 20) {
            if (empty($param['lianxu_rule'])) {
                return $this->renderError('至少添加一条规则');
            }
            $check = [];

            $days = count(array_unique(helper::getArrayColumn($param['lianxu_rule'], 'day')));

            foreach ($param['lianxu_rule'] as $k => $v) {
                if (!$v['day']) {
                    return $this->renderError('请添加天数');
                }
                if (!$v['num']) {
                    return $this->renderError('请添加赠送数量');
                }
                $check[] = $v['day'] . $v['num'];
                $v = $k;
            }
            if ($days != $v + 1) {
                return $this->renderError('请添加不同的天数');
            }
            if (count($check) != $v + 1) {
                return $this->renderError('添加不同规则');
            }
        } else {
            $data = [];
        }

        if ($model->edit('sign', $param)) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }
}
